<%@ page import="com.deepai.dprsmgr.utils.ErrCode" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" pageEncoding="utf-8" %>
<%@ taglib prefix="shiro" uri="http://shiro.apache.org/tags" %>
<%@include file="../base_path.jsp" %>
<html>
<head>
    <meta charset="utf-8">
    <meta name="renderer" content="webkit|ie-comp|ie-stand">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport"
          content="width=device-width,initial-scale=1,minimum-scale=1.0,maximum-scale=1.0,user-scalable=no"/>
    <meta http-equiv="Cache-Control" content="no-cache"/>
    <meta http-equiv="Expires" content="0">
    <meta http-equiv="Pragma" content="no-cache">
    <meta http-equiv="description" content="">
    <link rel="stylesheet" type="text/css" href="<%=basePath%>/lib/bootstrap/3.3.7/css/bootstrap.min.css"/>
    <link rel="stylesheet" type="text/css" media="screen"
          href="<%=basePath%>/lib/jqgrid/5.2.1/css/ui.jqgrid-bootstrap.css"/>
    <link rel="stylesheet" type="text/css" media="screen" href="<%=basePath%>/lib/lobibox/css/lobibox.min.css"/>
    <link type="text/css" rel="stylesheet"
          href="<%=basePath%>/lib/bootstrap-switch/css/bootstrap3/bootstrap-switch.min.css"/>
    <link type="text/css" rel="stylesheet" href="<%=basePath%>/lib/bootstrap-select/css/bootstrap-select.min.css"/>
    <link rel="stylesheet" type="text/css" media="screen" href="<%=basePath%>/css/mycss.css"/>

    <title>队列配置</title>
    <style>
        .header-right {
            position: absolute;
            bottom: 16px;
            right: 0px;
            top: 0px;
        }



        .head-search {
            right: 2px;

            height: 36px;
            border-radius: 5px;
            border: 1px solid #bcbec5;
            border: 1px solid #e8eaf3;
            background: #e8eaf3;
        }

        .head-search.empty_input input {
            height: 34px;
            width: 240px;
            border: none;
            border-radius: 5px;
            padding-left: 10px;
            color: #757b84;
            font-size: 14px;
            background: transparent;
        }

        .head-search input {
            height: 34px;
            width: 206px;
            border: none;
            border-radius: 5px;
            padding-left: 10px;
            color: #757b84;
            font-size: 14px;
            background: transparent;
        }

        .search-btn {
            float: right;
            width: 26px;
            height: 34px;
            padding: 8px;
            cursor: pointer;
            padding-left: 0px;
        }

        .clear-btn {
            float: right;
            width: 26px;
            height: 34px;
            padding: 8px;
            cursor: pointer;
            padding-left: 0px;
        }

        .empty_input .clear-btn {
            display: none;
        }

        /* popover样式 */
        .popover {
            position: absolute;
            top: 0;
            left: 0;
            z-index: 1060;
            display: none;
            max-width: 276px;
            padding: 1px;
            font-family: "Helvetica Neue",Helvetica,Arial,sans-serif;
            font-size: 14px;
            font-style: normal;
            font-weight: 400;
            line-height: 1.42857143;
            text-align: left;
            text-align: start;
            text-decoration: none;
            text-shadow: none;
            text-transform: none;
            letter-spacing: normal;
            word-break: normal;
            word-spacing: normal;
            word-wrap: normal;
            white-space: normal;
            background-color: #fff;
            -webkit-background-clip: padding-box;
            background-clip: padding-box;
            border: 1px solid #6097fe;
            /* border: 1px solid rgba(0,0,0,.2); */
            border-radius: 6px;
            -webkit-box-shadow: 0 5px 10px rgba(0,0,0,.2);
            box-shadow: 0 5px 10px rgba(0,0,0,.2);
            line-break: auto;
            background:#6097fe;
        }

        .popover.left>.arrow:after {
            right: 1px;
            bottom: -10px;
            content: " ";
            border-right-width: 0;
            border-left-color: #6097fe;
        }

        .popover h5 {
            color: #FFF;
        }

    </style>
</head>
<body>
<div class="navbar-fixed-top">
    <div class="breadcrumb" style="margin-bottom: 0;">
        <span>呼入中心</span>/
        <span class="active">队列配置</span>
        <span class="pull-right" title="刷新">
            <div class="btn-refresh" onclick="location.replace(location.href);">
            	<img src="<%=basePath%>/images/refresh.png" >
            </div>
        </span>

    </div>
</div>

<div class="container-fluid">
    <div class="container-fluid-main">
        <div class="page-header">
            <h3>队列配置</h3>

        </div>
        <div class="page-header">
            <div class="form-group">
                <div class="col-xs-2">
                    <div class="head-search ">
                        <input type="text" placeholder="请输入关键字" id="find" autocomplete="off">
                    </div>
                </div>
                <div class="col-xs-2">
                    <button class="btn btn-primary btn-sm" id="btn_query" type="button">查询</button>
                </div>
            </div>
        </div>
    </div>
    <table id="seatArrangementJQGrid"></table>
    <div style="height: 40px" id="seatArrangementJQGridPager"></div>
</div>


<!-- 模态框（Modal） -->
<div class="modal fade" id="modal_create_business" tabindex="-1" role="dialog" aria-labelledby="myModalLabel"
     aria-hidden="true">
    <div class="modal-dialog modal-lg" role="document">
        <div class="modal-content">

        </div>
    </div><!-- /.modal-content -->
</div><!-- /.modal -->
</div>

<!--_footer 作为公共模版分离出去-->
<script type="text/javascript" src="<%=basePath%>/lib/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript" src="<%=basePath%>/lib/bootstrap/3.3.7/js/bootstrap.js"></script>
<script type="text/javascript" src="<%=basePath%>/lib/bootbox/bootbox.min.js"></script>
<script type="text/javascript" src="<%=basePath%>/lib/jqgrid/5.2.1/js/i18n/grid.locale-cn.js"></script>
<script type="text/javascript" src="<%=basePath%>/lib/jqgrid/5.2.1/js/jquery.jqGrid.min.js"></script>
<script type="text/javascript" src="<%=basePath%>/lib/lobibox/js/lobibox.min.js"></script>
<script type="text/javascript" src="<%=basePath%>/lib/lobibox/js/messageboxes.min.js"></script>
<script type="text/javascript" src="<%=basePath%>/lib/lobibox/js/notifications.min.js"></script>
<!--/_footer 作为公共模版分离出去-->
<script type="text/javascript" src="<%=basePath%>/lib/bootstrap-switch/js/bootstrap-switch.min.js"></script>
<script type="text/javascript" src="<%=basePath%>/lib/bootstrap-select/js/bootstrap-select.min.js"></script>
<script type="text/javascript" src="<%=basePath%>/lib/bootstrap-select/js/i18n/defaults-zh_CN.js"></script>
<script type="text/javascript" src="<%=basePath%>/lib/jquery.validation/1.14.0/jquery.validate_1.js"></script>
<script type="text/javascript" src="<%=basePath%>/lib/jquery.validation/1.14.0/validate-methods.js"></script>
<script type="text/javascript" src="<%=basePath%>/lib/jquery.validation/1.14.0/messages_zh.js"></script>
<!--请在下方写此页面业务相关的脚本-->

<script type="text/javascript" src="<%=basePath%>/js/common.js"></script>
<script type="text/javascript">
    var keyword = '';
    $(function () {
        $.jgrid.defaults.responsive = true;
        $.jgrid.defaults.styleUI = "Bootstrap";
        $("#seatArrangementJQGrid").jqGrid({
            height: 434,
            autowidth: true,
            shrinkToFit: true, /*  autoScroll: false, *//*forceFit: true, */
            width:'100%',
            colNames: [  "主键","队列ID", "队列名称", "类型", "坐席分机", "操作"],
            colModel: [
                {name: "id", index: "id", hidden: true,key: true},
                {name: "queue", index: "queue", hidden: false},
                {
                    name: "queueName",
                    index: "queueName",
                    align: "left",
                    editable: true,
                    editrules: {required: true}
                },

                {name: "state", index: "state", align: "left", },

                {name: "agent", index: "agent", autowidth: true, align: "left"},
                {
                    name: "edit", index: "edit", align: "left",autowidth: true, hidden: function () {
                        <shiro:hasPermission name="caozuoyewu">
                        return false
                        </shiro:hasPermission>
                        return true
                    }()
                }
            ],
            pager: "#seatArrangementJQGridPager",
            viewrecords: true,
            hidegrid: false,
            multiselect: false,
            url: "<%=basePath%>/tiers/list.do",
            datatype: 'json',
            mtype: "POST",
            rownumbers: true,
            rownumWidth: 100,
            rowNum: 30,
            rowList: [15, 30, 50],
            jsonReader: {
                root: "dataList", page: "currPage", total: "totalPages",          //   很重要 定义了 后台分页参数的名字。
                records: "totalCount", repeatitems: false, id: "id"
            },
            loadComplete: function (data) {
                // 自动调整高度
                var resCount = data.records;
                var tableHeight = resCount * 30 + 40;
                $("#gbox_seatArrangementJQGrid .ui-jqgrid-bdiv").css(
                    "cssText",
                    "height: " + tableHeight + "px!important;");
            },
            gridComplete: function () {         // 数据加载完成后 添加 采购按钮
                $("#seatArrangementJQGrid").jqGrid('setLabel', 'rn', '序号', {
                    'text-align': 'center',
                    'font-size': '12px'
                }, '');
                var ids = jQuery("#seatArrangementJQGrid").jqGrid('getDataIDs');
                console.log(ids)
                for (var i = 0; i < ids.length; i++) {
                    var id = ids[i];

                    var editBtn = "<button type='button' class='edit btn btn-link btn-xs'  onclick='editBusiness(this, " + id + ")' style='margin-right: 2px'>编辑</button>" +
                        "<button type='button' class='save btn btn- link btn-xs hidden' onclick='saveBusiness(this, " + id + ")' style='margin-right: 2px' >保存</button>" +
                        "<button type='button'  class='cancel btn btn-link btn-xs hidden' onclick='cancelBusiness(this," + id + ")' style='margin-right: 2px' >取消</button>"
                    jQuery("#seatArrangementJQGrid").jqGrid('setRowData', ids[i], {edit: editBtn});


                }
            },
            beforeSelectRow: function (rowid, e) {
                var $myGrid = $(this),
                    i = $.jgrid.getCellIndex($(e.target).closest('td')[0]),
                    cm = $myGrid.jqGrid('getGridParam', 'colModel');
                return (cm[i].name != 'edit');
            },
            onSelectRow: function (rowid) {
//                showTaskInfo(rowid);
            },
            ondblClickRow: function (id) {
                <%--$("#modalCallInfo").modal({--%>
                <%--remote: '<%=basePath %>/call/callInfoShow.do?reserve_id=' + id--%>
                <%--});--%>
//                if (id && id !== lastSel) {
//                    jQuery('#blacklistJQGrid').jqGrid('restoreRow', lastSel);
//                    jQuery('#blacklistJQGrid').jqGrid('editRow', id, true);
//                    lastSel = id;
//                }
            },
            editurl: "<%=basePath %>/tiers/update.do"

        });

        <%--$("#btn_create_business").click(function () {--%>
        <%--    $("#modal_create_business").modal({--%>
        <%--        backdrop: false,--%>
        <%--        keyboard: false,--%>
        <%--        remote: '<%=basePath %>/business/showCreateBusinessPage.do'--%>
        <%--    });--%>
        <%--});--%>

        // $("#modal_create_business").on("hidden.bs.modal", function () {
        //     $(this).removeData("bs.modal");
        //     $(this).find(".modal-content").children().remove();
        //     refreshJQGrid();
        // });

        <%--$("#btn_export_business_list").click(function () {--%>
        <%--    var data = $("#seatArrangementJQGrid").jqGrid('getRowData');--%>
        <%--    if (data.length == 0) {--%>
        <%--        myNotify("warning", "", "暂无数据可导出！");--%>
        <%--    } else {--%>
        <%--        window.location.href = "<%=basePath%>/business/exportBusinessListExcel.do?keyword=" + keyword;--%>
        <%--    }--%>
        <%--});--%>

        $(document).on('keydown', 'body,#find', function (evt) { //回车发送
            evt.stopPropagation();
            var e = evt || event;
            if (e.keyCode === 13 && $('#find').is(':focus')) {
                search()
            }
        });
        $('.search-btn').click(function () {
            search();
        });
        $('#btn_query').click(function () {
            refreshJQGrid()
        });

        $('.clear-btn').click(function () {
            keyword = "";
            $('#find').val('');
            $('.head-search').addClass('empty_input');
            search();
        });

        $("#find").on("input propertychange change", function (e) {
            var val = $(this).val();
            if (val) {
                $('.head-search').removeClass('empty_input');
            } else {
                $('.head-search').addClass('empty_input');
            }
        })
    });

    /******************************方法声明**********************************/
    /**
     * 刷新表格数据
     */
    function refreshJQGrid() {
        var postData = {};
        postData.key = $("#find").val().trim();
        keyword = postData.key;
        $("#seatArrangementJQGrid").jqGrid("setGridParam", {
            url: "<%=basePath %>/tiers/list.do",
            mtype: 'POST',
            datatype: "json",
            postData: postData
        }).trigger("reloadGrid");
    }

    function search() {
        refreshJQGrid();
    }

    function businessDisable(obj, id) {
        bootbox.confirm({
            message: "停用后该业务下的所有任务将会终止，但外呼数据会保留，是否继续？",
            buttons: {
                confirm: {
                    label: '确认',
                    className: 'btn-success'
                },
                cancel: {
                    label: '取消',
                    className: 'btn-danger'
                }
            },
            callback: function (result) {

            }
        });

    }

    function businessEnable(obj, id) {
        bootbox.confirm({
            message: "启用后该业务下的所有任务不会启动，是否继续？",
            buttons: {
                confirm: {
                    label: '确认',
                    className: 'btn-success'
                },
                cancel: {
                    label: '取消',
                    className: 'btn-danger'
                }
            },
            callback: function (result) {
                if (result) {
                    var command = "enable";
                    $.ajax({
                        url: "<%=basePath%>/business/checkBusinessOrgStatus.do",
                        type: "post",
                        async: true,
                        data: "id=" + id + "&command=" + command,
                        dataType: "json",
                        success: function (data) {
                            if (data["errorCode"] == "0") {
                                // myNotify("success", "", data["msg"]);
                                businessOperate(obj, id, command);
//                                refreshJQGrid();
                            } else {
                                myNotify("error", "", "该组织已停用，无法启用该业务，若要启用，请先启用组织！");
                            }
                        },
                        error: function (data) {
                            myNotify("error", "", "操作请求发送过程中发生错误，请尽快联系管理员！");
                        }
                    });
                    // businessOperate(obj, id, command);
                }
            }
        });
    }

    function businessOperate(obj, id, command) {
        $.ajax({
            url: "<%=basePath%>/business/businessOperate.do",
            type: "post",
            async: true,
            data: "id=" + id + "&command=" + command,
            dataType: "json",
            success: function (data) {
                if (data["errorCode"] === "0") {
                    myNotify("success", "", data["msg"]);
                    refreshJQGrid();
                } else {
                    myNotify("error", "", data["msg"]);
                }
            },
            error: function (data) {
                myNotify("error", "", "操作请求发送过程中发生错误，请尽快联系管理员！");
            }
        });
    }

    function cancelBusiness(obj, id) {
        $('#seatArrangementJQGrid').restoreRow(id);
        $("#seatArrangementJQGrid #"+id).find(".save,.cancel").addClass("hidden");
        $("#seatArrangementJQGrid #"+id).find(".edit").removeClass("hidden");
    }

    // 编辑业务名称
    function editBusiness(obj, id) {
        $(obj).addClass("hidden");
        $(obj).parent().children(".save").removeClass("hidden");
        $(obj).parent().children(".cancel").removeClass("hidden");
        $("#seatArrangementJQGrid").jqGrid("editRow", id);
    }

    // 保存业务名称
    function saveBusiness(obj, id) {
        var reg = /^[\w\u4e00-\u9fa5]+$/;
        var name = $("#"+id+'_queueName').val();
        console.log(name)
        var check = CheckName(name, true, false, true);
        var regComment = /[^\a-\z\A-\Z0-9\u4E00-\u9FA5\ ,_]/g;
        // 验证业务名称
        if (!check.pass) {
            myNotify("error", "", "队列名称" + check.msg);
            refreshJQGrid();
            return false;
        }
        // if (!checkNameUnique(id, name)) {
        //     myNotify("error", "", "业务名称已存在，请重新输入");
        //     return false;
        // }
        if (regComment.test(name)) {
            myNotify("error", "", "队列名称有特殊字符，只能包含中文、英文、数字、下划线");
            refreshJQGrid();
            return false;
        }
        if (name.length > 30) {
            myNotify("error", "", "队列名称最多输入30个字");
            refreshJQGrid();
            return false;
        }
        $("#seatArrangementJQGrid").jqGrid("saveRow", id, onSaveResponse);
    }

    // 处理响应结果
    function onSaveResponse(response) {
        console.log(response)
        if (response.responseJSON.errorCode == "0") {
            myNotify("success", "", "保存成功！");
        } else if (response.responseJSON.errorCode == "500") {
            myNotify("error", "", "队列名称重复！");
            refreshJQGrid();
            return;
        } else {
            myNotify("error", "", "保存失败！");
        }
        refreshJQGrid();
    }

    function checkNameUnique(id, name) {
        var checkBusinessNameUrl = "<%=basePath%>/tiers/queryQueueName.do";
        var flag;
        $.ajax({
            url: checkBusinessNameUrl,
            type: "post",
            async: false,
            data: {
                businessId: id,
                type: 1,
                businessName: name,
            },
            dataType: "json",
            success: function (data) {
                console.log(data)
                if (data.errorCode == "0") {
                    flag = true;
                } else {
                    flag = false;
                }
            },
            error: function (data) {
                myNotify("error", "", "向服务器发送删除请求过程中发生错误！");
            }
        });

        return flag
    }

</script>
</body>
</html>